package pers.qianyu.month_202011.date_20201125;

/**
 * 5. 最长回文子串
 * https://leetcode-cn.com/problems/longest-palindromic-substring/
 *
 * @author mizzle rain
 * @date 2020-11-25 17:01
 */
public class LongestPalindrome {
    public String longestPalindrome(String s) {
        int[] res = new int[2];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int[] arr1 = find(s, i, i);
            int[] arr2 = find(s, i, i + 1);
            res = res[1] - res[0] > arr1[1] - arr1[0] ? res : arr1;
            res = res[1] - res[0] > arr2[1] - arr2[0] ? res : arr2;
        }
        return s.substring(res[0], res[1]);
    }

    private int[] find(String s, int p1, int p2) {
        while (p1 >= 0 && p2 < s.length() && s.charAt(p1) == s.charAt(p2)) {
            p1--;
            p2++;
        }
        return new int[]{p1 + 1, p2};
    }

    public static void main(String[] args) {
        String result = new LongestPalindrome().longestPalindrome("babad");
        System.out.println("result = " + result);
    }
}
